package com.kanshu.ksgb.fastread.doudou.module.login.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.event.LoginEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ActivateService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.module.download.service.DownloadBookService;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UserBean;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterPresenter;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService;
import com.ss.android.common.lib.AppLogNewUtils;
import com.ss.android.common.lib.EventUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.kanshu.ksgb.fastread.doudou.module.personal.activity.BindPhoneActivity.VALIDATION_EXPIRE_TIME;

/**
 * Created by xubo on 2018/11/16
 */
@SuppressLint("SetTextI18n")
@Route(path = ARouterConfig.PERSONAL_LOGIN_IN)
public class LoginActivity extends BaseActivity {
    private static final String NEW_USER = "1";//新用户
    private static String INTENT_PHONE = "phone";
    @BindView(R.id.input_phone)
    EditText mInputPhone;
    @BindView(R.id.input_validation_code)
    EditText mAlidationCode;
    @BindView(R.id.send_validation_code)
    TextView mSendValidationCode;
    @BindView(R.id.input_invitation_code)
    EditText mInvitationCode;

    PersonCenterPresenter mPresenter = new PersonCenterPresenter(lifeCyclerSubject);

    private String mPhone = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setTitle("手机快速登录");
        mPhone = getIntent().getStringExtra(INTENT_PHONE);
        if (!TextUtils.isEmpty(mPhone)) {
            mInputPhone.setText(mPhone);
        }
    }

    @OnClick({R.id.send_validation_code, R.id.user_login})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_login:
                if (TextUtils.isEmpty(mInputPhone.getText().toString().trim()) || mInputPhone.getText().toString().trim().length() != 11) {
                    ToastUtil.showMessage("输入的手机号码格式不正确");
                    return;
                }
                if (TextUtils.isEmpty(mAlidationCode.getText().toString().trim()) || mAlidationCode.getText().toString().trim().length() != 4) {
                    ToastUtil.showMessage("输入的验证码格式不正确");
                    return;
                }
                showLoading("");
                mPresenter.userLogin(mInputPhone.getText().toString().trim(), mAlidationCode.getText().toString().trim(),
                        mInvitationCode.getText().toString().trim(), new INetCommCallback<BaseResult<UserBean>>() {

                    @Override
                    @SuppressLint("ApplySharedPref")
                    public void onResponse(BaseResult<UserBean> result) {
                        dismissLoading();
                        if(result.result != null && result.result.data != null) {
                            if(result.result.status.code == 0) {
                                //DownloadBookService.clearAll();
                                ARouter.getInstance().navigation(ActivateService.class).clearQueue();
                                //切换账号，旧账号设置为游客模式并上报头条事件(自定义游客模式事件)
                                if (!TextUtils.equals(result.result.data.user_id, UserUtils.getUserId()) && MMKVUserManager.getInstance().isUserLogin()) {
                                    AdPresenter.touTiaoEvent(R.string.tourists_mode_event,getString(R.string.TOU_TIAO_USER_ID),UserUtils.getUserId());
                                }
                                // 切换账号 之前登录的账号  登录态置为 未登录
                                MMKVUserManager.getInstance().setLoginState(Constants.LoginState.TYPE_NO_LOGIN);
                                // 切换到当前登录状态
                                UserUtils.saveUserId(result.result.data.user_id);
                                //新用户上报头条为注册事件，老用户上报头条为登录事件
                                if (TextUtils.equals(result.result.data.is_new_user, NEW_USER)) {
                                    EventUtils.setRegister("mobile", true);
                                } else {
                                    EventUtils.setLogin("mobile", true);
                                }
                                MMKVUserManager.getInstance().setLoginBeans(result.result.data.beans_balance);
                                MMKVUserManager.getInstance().setLoginState(Constants.LoginState.TYPE_HAS_LOGIN);
                                MMKVUserManager.getInstance().setLoginToken(result.result.data.token);
                                MMKVUserManager.getInstance().setLoginSex(result.result.data.sex);
                                LoginEvent event = new LoginEvent();
                                event.is_new_user = result.result.data.is_new_user;
                                EventBus.getDefault().post(event);
                                // 登录用户 为 掉线用户时 或者未登录直接登录用户  则继续掉线之前操作，否则回到主页
                                boolean flag = TextUtils.equals(MMKVDefaultManager.getInstance().getOfflineUserId(), "") || TextUtils.equals(MMKVDefaultManager.getInstance().getOfflineUserId(), result.result.data.user_id);
                                MMKVDefaultManager.getInstance().setOfflineUserId("");
                                if(flag){
                                    finish();
                                }else{
                                    ARouterUtils.toActivity(ARouterConfig.HOME_PAGE);
                                }
                            } else {
                                ToastUtil.showStaticMessage(result.result.status.msg);
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        dismissLoading();
                        ToastUtil.showStaticMessage(errDesc);
                    }
                });
                break;
            case R.id.send_validation_code:
                if (TextUtils.isEmpty(mInputPhone.getText().toString()) || mInputPhone.getText().toString().length() != 11) {
                    ToastUtil.showStaticMessage("输入的手机号码格式不正确");
                    return;
                }
                mSendValidationCode.setEnabled(false);
                RetrofitHelper helper = RetrofitHelper.getInstance();
                PersonCenterService personService = helper.createService(PersonCenterService.class);
                Map<String, String> map = new HashMap<>();
                map.put("phone", mInputPhone.getText().toString());
                personService.getValidateCode(map).compose(asyncRequest()).subscribe(new Observer<BaseResult<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading("");
                    }

                    @Override
                    public void onNext(BaseResult<String> stringBaseResult) {
                        if (stringBaseResult.result.status.code == 0) {
                            ToastUtil.showStaticMessage("获取验证码成功");
                            startCountDown();
                        } else {
                            ToastUtil.showStaticMessage("获取验证码失败,请稍后再试");
                            mSendValidationCode.setEnabled(true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showStaticMessage("获取验证码失败,请稍后再试");
                        e.printStackTrace();
                        mSendValidationCode.setEnabled(true);
                        dismissLoading();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
                break;
        }
    }


    private void startCountDown() {
        Observable.intervalRange(1, VALIDATION_EXPIRE_TIME + 1, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(lifeCyclerSubject)
                .subscribe(aLong -> updateContDownView(VALIDATION_EXPIRE_TIME - aLong));
    }

    private void updateContDownView(Long timeLeft) {
        if (timeLeft <= 0) {
            mSendValidationCode.setEnabled(true);
            mSendValidationCode.setText("获取验证码");
            return;
        }
        mSendValidationCode.setText(timeLeft + "s");
    }

    public static void actionStart(Context context, String phone) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(INTENT_PHONE, phone);
        context.startActivity(intent);
    }
}
